# frozen_string_literal: true

module Resolvers
  module Ai
    class ExplainVulnerabilityPromptResolver < BaseResolver
      include Gitlab::Graphql::Authorize::AuthorizeResource

      type Types::Ai::Prompt::ExplainVulnerabilityPromptType, null: true

      calls_gitaly!

      authorize :read_vulnerability

      argument :vulnerability_id, ::Types::GlobalIDType[::Vulnerability],
        required: true,
        description: 'Vulnerability to generate a prompt for.'

      def resolve(vulnerability_id:)
        vulnerability = authorized_find!(vulnerability_id)
        {
          prompt_with_code: prompt(vulnerability).to_prompt(include_source_code: true),
          prompt_without_code: prompt(vulnerability).to_prompt(include_source_code: false),
          presubmission_checks: prompt(vulnerability).presubmission_checks
        }
      end

      private

      def find_object(vulnerability_id)
        GitlabSchema.find_by_gid(vulnerability_id)
      end

      def prompt(vulnerability)
        @prompt ||= completion[:prompt_class].new(vulnerability)
      end

      def completion
        Gitlab::Llm::CompletionsFactory::COMPLETIONS[:explain_vulnerability]
      end
    end
  end
end
